package com.liang.maogouyuyin;

/**
 * 启动页
 * <p>
 *
 *
 * @version 1.0
 */

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bytedance.sdk.openadsdk.mediation.manager.MediationSplashManager;

import com.liang.publics.ad.TTAdManagerHolder;
import com.liang.publics.ad.ads.MediationSplashService;
import com.liang.publics.base.BaseActivity;
import com.liang.publics.callback.DialogCallBack;
import com.liang.publics.callback.OnResponseListener;
import com.liang.publics.config.Const;
import com.liang.publics.ui.AgreementDialog;
import com.liang.publics.util.DeviceUtils;
import com.liang.publics.util.HttpUtilSS;
import com.liang.publics.util.LogUtil;
import com.liang.publics.util.MyStringUtil;
import com.liang.publics.util.SharedPreferencesUtil;
import com.liang.publics.util.UmengUtil;
import com.liang.publics.util.oaid.DemoHelper;
import com.liang.publics.util.oaid.DemoHelperHuawei;
import com.liang.publics.util.oaid.StringId;
import com.umeng.umcrash.UMCrash;
import com.yl.adsdk.YlLib;

import java.util.HashMap;
import java.util.Map;

@SuppressLint("CustomSplashScreen")
public class SplashActivity extends BaseActivity implements  DemoHelper.AppIdsUpdater, DemoHelperHuawei.AppIdsUpdater ,UmengUtil.AppIdsUpdater{

    // 启动APP后进入该页面进行预加载1.5S，之后跳转到首页
    public static int sssssss=0;
    //-----------------------public公共------------s
    public static String mymanufacturer="" ;
    private int duration = 10000;
    public static DemoHelper demoHelper;

    public static String odid;
    public static String oaidYm;
    public static String oaidHw;
    public static String androidId;

    public static String mac = "";
    public static String imei = "";
    private CountDownTimer timer;

    public static Boolean intiAd = false;
    public static String packageName;
    public static int versionCode;
    public static String versionName;
    public String ecpm = "";
    public boolean ifloadAndShowSplashAd = true;
    public boolean onSplashLoadSuccess = false;
    public boolean onSplashAdShow = false;
    //是否跳过开屏
    public static boolean ifSplashActivity = true;
    @SuppressLint("StaticFieldLeak")
    public static Context context = null;
    @SuppressLint("StaticFieldLeak")
    public static Activity activity = null;

    public static MediationSplashManager manager;

    public static String userNo = null;
    String downloadChannel;
    UmengUtil umengUtil = null;

    public static void gotoActivity(Intent intent) {
        context.startActivity(intent);
    }

    public static void startActivity(Activity activity) {
        Intent intent = new Intent(activity, SplashActivity.class);
        activity.startActivity(intent);
    }

    //-----------------------public公共------------e
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TheBaseApplication.ifMainActivity = true;
        SplashActivity.ifSplashActivity = true;
        setContentView(R.layout.public_activity_splash);

        //---------------------public 公共需要
        if (!SharedPreferencesUtil.getStatus("sttttt")) {
            SharedPreferencesUtil.saveStatus("sttttt",true);
        } else {
            sssssss=-1;
        }
        //初始化参数
        initPackage();
        if (SharedPreferencesUtil.getAgreementStatus()) {//隐私授权后每次登录
            updateConfigAd(this);//更新审核状态
        }
        onSplashAdShow = false;
        onSplashLoadSuccess = false;
        ifSplashActivity = true;
        context = this;
        activity = this;
        if (!SharedPreferencesUtil.getAgreementStatus()) {
            TextView textView = findViewById(R.id.tvTips);
            textView.setText("首次猫狗人交流翻译器加载中,请稍后...");
        } else {
            TextView textView = findViewById(R.id.tvTips);
            textView.setText("猫狗人交流翻译器加载中,请稍后...");
        }
        //友盟
        if (Const.IF_UM) {
            umengUtil =  new UmengUtil();
            umengUtil.initConfig(context);
        }
        //隐私提示框
        checkShowAgreementDialog();
    }

    public void initPackage(){

        try {
            mymanufacturer = MyStringUtil.getmanufacturer(Build.MANUFACTURER);

            packageName = getPackageName();
            PackageInfo packageInfo = getPackageManager().getPackageInfo(packageName, 0);
            versionName = packageInfo.versionName;
            versionCode = packageInfo.versionCode;

            HttpUtilSS.XUpUA = packageName+"/"+versionName;
        } catch (Exception e) {
            if (Const.IF_UM) {
                UMCrash.generateCustomLog(e, "packageName");
            }
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
    //--------------------------------------------------public 公共需要

    // 隐私弹窗
    private void checkShowAgreementDialog() {
        if (!SharedPreferencesUtil.getAgreementStatus()) {
            AgreementDialog.showDialog(this, new DialogCallBack() {
                @Override
                public void buAgree() {
                    SharedPreferencesUtil.saveAgreementStatus(true);
                    initData("1");
                }

                @Override
                public void disagree() {
                    finish();
                }
            });
        } else {
            initData("2");
        }
    }

    //更新后台配置
    public  static void updateConfigAd(Activity activity) {
        try {
            Map<String, String> map = getPackages();
            new Thread(new Runnable() {
                @Override
                public void run() {


                    String url = Const.URL_Q + "/dj-tools-api/app/v2/config";
                    HttpUtilSS.getRequestConfig(url, map, new OnResponseListener() {
                        @Override
                        public void onSuccess(String response) {
                            intiAd();
                        }

                        @Override
                        public void onError(String responseBody, String error) {
                            SharedPreferencesUtil.saveStatus(SharedPreferencesUtil.IF_AD, Const.ifAd);
                            SharedPreferencesUtil.saveStatus(SharedPreferencesUtil.IF_AD_2, false);
                            LogUtil.d(Const.TAG, url + "---err-------:" + map.toString() + "----------:" + responseBody + "----------:" + error);

                        }
                    });
                }
            }).start();

        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static Map<String, String> getPackages() {
        Map<String, String> map = new HashMap<>();
        map.put("pkgName", packageName);
        map.put("version", Build.VERSION.RELEASE);
        map.put("appVersion", versionName);
        map.put("djId", SharedPreferencesUtil.getString("djId"));
        return map;
    }

    public Map<String, String> getPackage(){

        Map<String, String> map = new HashMap<>();
        map.put("key", packageName);
        map.put("pkgName", packageName);

        odid = SharedPreferencesUtil.getString("oaid");
        oaidHw = SharedPreferencesUtil.getString("oaidHw");
        oaidYm = SharedPreferencesUtil.getString("oaidYm");
        androidId = SharedPreferencesUtil.getString("androidId");
        mac = SharedPreferencesUtil.getString("mac");
        imei = SharedPreferencesUtil.getString("imei");
        map.put("oaId", odid);
        map.put("oaIdU", oaidYm);//友盟
        map.put("oaIdH", oaidHw);//华为
        map.put("imei", imei);
        map.put("mac", mac);
        map.put("androidId", androidId);
        map.put("appVersion", versionName);
        map.put("osVersion", Build.VERSION.RELEASE);
        map.put("deviceBrand", Build.MANUFACTURER);
        map.put("deviceModel", Build.MODEL);

        try {
            map.put("deviceTag", YlLib.getRiskInfo(this));
        }catch (Exception e){
            e.printStackTrace();
        }
        try {//渠道
            downloadChannel= context.getString(R.string.downloadChannel);
            if(downloadChannel!=null && !downloadChannel.isEmpty()) {
                map.put("downloadChannel", downloadChannel);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        map.put("charge", DeviceUtils.isBatteryCharging(this) );//0:未充电、1:充电
        map.put("zz", String.valueOf(System.currentTimeMillis()));
        return  map;
    }
    boolean ifGetConfigAd = false;
    public void getConfigAd() {
        try {
            if (ifGetConfigAd) {
                return;
            } else {
                ifGetConfigAd = true;
            }

            Map<String, String> map = getPackage();

            if (Const.ifAd) {//本地测试时
                SharedPreferencesUtil.saveStatus(SharedPreferencesUtil.IF_AD, Const.ifAd);
            } else {

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        String url = Const.URL_Q + "/dj-tools-api/app/v2/install";
                        HttpUtilSS.getRequest(url, map, new OnResponseListener() {
                            @Override
                            public void onSuccess(String response) {
                                intiAd();
                            }

                            @Override
                            public void onError(String responseBody, String error) {
                                LogUtil.d(Const.TAG, url + "---err-------:" + map + "----------:" + responseBody + "----------:" + error);
                                SharedPreferencesUtil.saveStatus(SharedPreferencesUtil.IF_AD, Const.ifAd);
                            }
                        });
                    }
                }).start();
            }
        } catch (Exception e) {

            if (Const.IF_UM) {
                UMCrash.generateCustomLog(e, "installHttp");
            }
            e.printStackTrace();
            //ad标志
            SharedPreferencesUtil.saveStatus(SharedPreferencesUtil.IF_AD, Const.ifAd);
        }
    }

    private void initData(String type) {
        if (sssssss > 0)
            return;
        if (sssssss == -1)
            type = "2";
        else sssssss++;
        if ("1".equals(type)) {
            duration = duration + 2000;

            //缓存唯一标识
            try {
                StringId.idCache(this);
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                if(umengUtil!=null) {
                    umengUtil.getOaid(this,this);
                }
            } catch (Exception e){
                e.printStackTrace();
            }

            try {
                demoHelper = new DemoHelper(this, Const.lib);
                SplashActivity.demoHelper.getDeviceIds(this, true, false, false);
            }catch (Exception e){
                e.printStackTrace();
            }

            try {
                if("huawei".equals(SplashActivity.mymanufacturer)) {
                    new DemoHelperHuawei().getOaid(this, this);
                }
            }  catch (Exception e){
                e.printStackTrace();
            }
        }

        //友盟
        if (Const.IF_UM) {
            new UmengUtil().init(context);
        }

        ProgressBar pbProgress = findViewById(R.id.pbProgress);
        timer = new CountDownTimer(duration, 200) {
            int progress = 0;

            @Override
            public void onTick(long millisUntilFinished) {
                boolean ifAdBo = SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD);
                if (!ifAdBo) {
                    ifAdBo = SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD_2);
                }

                float num = (duration - millisUntilFinished) / (float) duration * 100;
                LogUtil.i(Const.TAG, "initData------------" + duration + ":" + num + "--------sInitOk:" + TTAdManagerHolder.sInitOk + "-------------------------sInitSplashOk:" + TTAdManagerHolder.sInitSplashOk + "----------------ifAd:" + ifAdBo);
                progress = (int) num; // 每次增加指定的进度值
                pbProgress.setProgress(progress);

                if(userNo != null){
                    TextView users =  findViewById(R.id.userNo);
                    users.setText("NO:"+userNo);
                }

                if (ifAdBo && TTAdManagerHolder.sInitSplashOk) {
                    LogUtil.i(Const.TAG, "aaaaaaaaaaaaaaa------------" + duration + ":" + num + "----ifloadAndShowSplashAd：" + ifloadAndShowSplashAd +
                            "-----ifSplashActivity:" + ifSplashActivity + "----onSplashAdShow1:" + MediationSplashService.onSplashAdShow1 + "----onSplashAdShow2:" + MediationSplashService.onSplashAdShow2);

                    LogUtil.i(Const.TAG, "ccccccccccccccc------------" + duration + ":" + num + "------------ifSplashActivity:" + ifSplashActivity
                            + "(----onSplashAdShow2:" + MediationSplashService.onSplashAdShow2 + "---------------doubleShowOK1:" + MediationSplashService.doubleShowOK1 +
                            ")----(onSplashAdShow1:" + MediationSplashService.onSplashAdShow1 + "---------------doubleShowOK2:" + MediationSplashService.doubleShowOK2 + ")"
                            + "----(onSplashRenderSuccess1:+" + MediationSplashService.onSplashRenderSuccess1 + "----------onSplashRenderSuccess2:" + MediationSplashService.onSplashRenderSuccess2 + ")"
                    );

                    // 加载并展示广告
                    if (ifloadAndShowSplashAd) {
                        ifloadAndShowSplashAd = false;
                        loadAndShowSplashAd();
                    } else if (
                            (num > 90 && ifSplashActivity && MediationSplashService.onSplashAdShow1 == false && MediationSplashService.onSplashAdShow2 == false)//超时没显示(9S)
                                    || (num > 80 && ifSplashActivity && MediationSplashService.onSplashRenderSuccess1 == false && MediationSplashService.onSplashRenderSuccess2 == false)//超时广告未初始化完成 （8s）
                    ) {
                        timer.cancel();
                        MainActivity.gotoActivity(SplashActivity.this);
                        LogUtil.i(Const.TAG, "MainActivity--11111111111111111111111111");
                        finish();
                    }
                } else if ((num > 70 && !ifAdBo) //不加载广告
                        || (num > 80 && TTAdManagerHolder.sInitSplashOk == false)) {//超时、无AD
                    LogUtil.i(Const.TAG, "bbbbbbbbbbbbb------------" + duration + ":" + num + "--------sInitOk:" + TTAdManagerHolder.sInitOk + "-------------------------sInitSplashOk:" + TTAdManagerHolder.sInitSplashOk + "----------------ifAd:" + ifAdBo);

                    if (ifSplashActivity) {
                        timer.cancel();
                        MainActivity.gotoActivity(SplashActivity.this);
                        LogUtil.i(Const.TAG, "GuideOptimizeActivity--222222222222222222222222");
                        finish();
                    }
                }
            }

            @Override
            public void onFinish() {
                pbProgress.setProgress(100);
                //gotoNextActivity();
            }
        };
        timer.start();
    }

    public boolean ifOaid = false;
    public boolean ifOaidHw = false;
    public boolean ifOaidYm = false;
    @Override
    public void onIdsValid(String oaid, String vaid, String aaid) {
        Log.d(Const.TAG, "s---onIdsValid--------获取接口配置---oaid:" + oaid + "---vaid:" + vaid + "---aaid:" + aaid);
        ifOaid = true;
        oaidIfGetConfigAd();
        Log.d(Const.TAG, "e----onIdsValid-------获取接口配置");
    }

    @Override
    public void onIdsValid(String oaid) {//华为
        Log.d(Const.TAG, "s---onIdsValid--hw------获取接口配置---oaid:" + oaid );
        ifOaidHw=true;
        oaidIfGetConfigAd();
        Log.d(Const.TAG, "e----onIdsValid--hw-----获取接口配置");
    }

    @Override
    public void onIdsValidUm(String oaid) {//友盟
        Log.d(Const.TAG, "s---onIdsValid--um------获取接口配置---oaid:" + oaid );
        ifOaidYm = true;
        oaidIfGetConfigAd();
        Log.d(Const.TAG, "e----onIdsValid--um-----获取接口配置");
    }

    public int oaidIfGetConfigAdCount = 0;
    public void  oaidIfGetConfigAd() {
        oaidIfGetConfigAdCount++;
        if ("huawei".equals(mymanufacturer)) {//华为需要三个oaid
            if (ifOaid && ifOaidHw && ifOaidYm) {
                //获取接口配置
                getConfigAd();
            } else if (oaidIfGetConfigAdCount == 1) {
                configAdJob();
            }

        } else {
            if (ifOaid &&  ifOaidYm) {
                getConfigAd();
            } else if (oaidIfGetConfigAdCount == 1) {
                configAdJob();
            }
        }
    }

    public void configAdJob(){

        try {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.postDelayed(
                    () -> getConfigAd(), 1000
            );
        } catch (Exception e) {
            e.printStackTrace();
            getConfigAd();
        }
    }

    private void loadAndShowSplashAd() {
        MediationSplashService mediationSplashService = new MediationSplashService();
        mediationSplashService.intiDate(context, activity, findViewById(R.id.fl_content), getResources().getString(R.string.splash_media_id), getResources().getString(R.string.splash_media_id_s), findViewById(R.id.fl_content), getResources().getString(R.string.splash_media_2_id), getResources().getString(R.string.splash_media_2_id_s));
    }

    private void startMusicActivity(String type) {
        LogUtil.i(Const.TAG, "startMainActivity--" + type);
        MainActivity.gotoActivity(context);
        finish();
    }

    public static void intiAd() {
        if (SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD) || SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD_2)) {
            if (!intiAd) {
                intiAd = true;
                //穿山甲SDK初始化
                //强烈建议在应用对应的Application#onCreate()方法中调用，避免出现context为null的异常
                TTAdManagerHolder.init(context);
                TTAdManagerHolder.start(context);

                //--------------adspark
                //           上报事件初始化
                if (Const.IF_ADSPARK) {
                    //InitConfig config = new AdSparkUtils().initConfig(context, activity);
                } else {
                    //new GravityUtils().initConfig(context);
                }
            }
        }
    }
}